<template>
  <div class="">
    <my-header>
      <span>郑州</span>
    </my-header>
    <my-input v-model="keyword" />
    <button @click="search">提交</button>

    <ul class="con">
      <h1>搜索结果</h1>
      <li v-for="item in result" :key="item.id + '1'" @click="gotoList(item)">
        {{ item.title }}
      </li>
    </ul>

    <ul class="con" v-if="result.length == 0 && history.length != 0">
      <h1>历史记录</h1>
      <li v-for="(item, index) in history" :key="index" @click="gotoList(item)">
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import myHeader from "../components/myHeader.vue";
import myInput from "../components/myInput.vue";
import searchData from "../../public/data.json";
export default {
  setup(props, ctx) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const data = reactive({
      keyword: "",
      //搜索关键字
      result: [],
      //搜到的结果
      history: JSON.parse(localStorage.getItem("history")) || [],
    });
    const search = () => {
      data.result = searchData.list.filter((item) => {
        return item.title.includes(data.keyword);
      });
    };
    //搜索方法

    const gotoList = (item) => {
      data.history.splice(4, 1);
      data.history.unshift(item);
      localStorage.setItem("history", JSON.stringify(data.history));
      router.push({
        path: "/about",
        query: {
          title: item.title,
          ...item.location,
        },
      });
    };
    //历史记录最多存五条

    return { ...toRefs(data), search, gotoList };
  },
  components: {
    myHeader,
    myInput,
  },
};
</script>

<style lang="scss">
.con {
  li {
    height: 30px;
    border: 1px solid #ccc;
    line-height: 30px;
  }
}
</style>
